<template>
    <div class="container">
        <el-table :data="tableData.data" style="width: 100%;margin-top: 20px;">
            <el-table-column prop="id" label="ID" width="100"></el-table-column>
            <el-table-column prop="answer" label="问题" width="200"></el-table-column>
            <el-table-column prop="answeredBy" label="回答" width="300">
                <template #default="scope">
                    <el-input v-if="scope.row.editing" v-model="scope.row.answeredBy" type="textarea" rows="3"></el-input>
                    <span v-else>{{ scope.row.answeredBy || '暂无回复' }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="userId" label="用户ID" width="100"></el-table-column>
            <el-table-column prop="createdAt" label="提问时间" width="180">
                <template #default="scope">
                    {{ new Date(scope.row.createdAt).toLocaleString() }}
                </template>
            </el-table-column>
            <el-table-column prop="updatedAt" label="回复时间" width="180">
                <template #default="scope">
                    {{ scope.row.updatedAt ? new Date(scope.row.updatedAt).toLocaleString() : '未回复' }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
                <template #default="scope">
                    <el-button v-if="!scope.row.editing" size="small" type="primary" plain @click="startEdit(scope.row)">
                        {{ scope.row.answeredBy ? '修改回复' : '回复' }}
                    </el-button>
                    <template v-else>
                        <el-button size="small" type="success" plain @click="saveAnswer(scope.row)">保存</el-button>
                        <el-button size="small" plain @click="cancelEdit(scope.row)">取消</el-button>
                    </template>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination 
            background 
            layout="prev, pager, next" 
            :total="total" 
            :page-size="pageSize"
            :current-page="currentPage" 
            @current-change="handlePageChange" 
            @size-change="handlePageSizeChange"
            style="margin-top: 20px; display: flex; justify-content: center;" 
        />
    </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const baseURL = 'http://localhost:9090/api/question-answer';

const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const tableData = reactive({ data: [] });

const handlePageChange = (page: number) => {
    currentPage.value = page;
    fetchTableData();
}

const handlePageSizeChange = (size: number) => {
    pageSize.value = size;
    fetchTableData();
}

function fetchTableData() {
    axios.get(`${baseURL}/`).then((res) => {
        tableData.data = res.data.map((item: any) => ({
            ...item,
            id: String(item.id),
            editing: false,
            originalAnsweredBy: item.answeredBy
        }));
        total.value = res.data.length;
    }).catch(error => {
        ElMessage.error('加载数据失败');
    });
}

function startEdit(row: any) {
    row.editing = true;
    row.originalAnsweredBy = row.answeredBy;
}

function cancelEdit(row: any) {
    row.editing = false;
    row.answeredBy = row.originalAnsweredBy;
}

function saveAnswer(row: any) {
    const updatedQuestion = {
        id: String(row.id),
        answer: row.answer,
        answeredBy: row.answeredBy,
        userId: row.userId,
        createdAt: row.createdAt,
        updatedAt: new Date().toISOString()
    };

    axios.put(`${baseURL}/`, updatedQuestion).then(() => {
        console.log(updatedQuestion);
        row.editing = false;
        ElMessage.success('回复成功');
        fetchTableData();
    }).catch(() => {
        ElMessage.error('回复失败');
    });
}

// 初始加载数据
fetchTableData();
</script>

<style scoped>
.container {
    padding: 20px;
}

.el-table {
    margin-bottom: 20px;
}

.el-pagination {
    text-align: center;
}
</style>